package com.heima.wemedia.interceptor;

import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: Tangguo
 * @Date: 2023-06-08  11:02
 */
@Component
@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String userId=request.getHeader("userId");
       if(!StringUtils.isBlank(userId)){
           //存入ThreadLocal
           log.info("设置用户信息到threadlocal中...");
           //把用户id存入threadloacl中
           WmUser wmUser = new WmUser();
           wmUser.setId(Integer.valueOf(userId));
           WmThreadLocalUtil.setUser(wmUser);
       }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       //清理ThreadLocal
        log.info("清理threadlocal...");
        WmThreadLocalUtil.clear();

    }
}
